<template>
  <div class="app-container">
    <!--工具栏-->
    <div
      v-loading="loading"
      class="head-container"
      element-loading-text="数据同步中"
    >
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!-- <crudOperation :permission="permission" /> -->
      <el-button
        class="filter-item"
        type="warning"
        icon="el-icon-refresh"
        size="mini"
        @click="asyncFiled"
      >同步源字段</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        size="mini"
        @click="asyncTargetFiled"
      >复制到目标字段</el-button>
      <el-button
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        size="mini"
        @click="toDelete(crud.selections)"
      >删除</el-button>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="targetFieldShow"
        title="选择字段"
        width="820px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="80px"
        >
          <div v-if="sourceTableArr.length > 0" class="check_ul">
            <span
              v-for="(item, index) in sourceTableArr"
              :key="index"
              :class="item.checked ? 'li_checked' : ''"
              class="check_li"
              @click="checkFieldItem(index, item.label, item.value)"
            >{{ item.value }}</span>
          </div>
          <div v-else class="check_ul">暂无数据</div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="text"
            @click="targetFieldShow = false"
          >取消</el-button>
        </div>
      </el-dialog>
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="80px"
        >
          <el-form-item label="源字段类型(字段，自定义)">
            <el-input v-model="form.sourceType" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="源字段">
            <el-input v-model="form.sourceCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="原字段长度">
            <el-input v-model="form.sourceSize" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="表主键字段">
            <el-input v-model="form.targetCode" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.memo" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="对应规则">
            <el-input v-model="form.migRule" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="扩展类">
            <el-input v-model="form.extClass" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="扩展属性">
            <el-input v-model="form.extJson" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="启用">
            <el-input v-model="form.delFlag" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="添加时间">
            <el-input v-model="form.createTime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="修改时间">
            <el-input v-model="form.updateTime" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.cu === 2"
            type="primary"
            @click="crud.submitCU"
          >确认</el-button>
        </div>
      </el-dialog>
      <el-dialog title="提示" :visible.sync="dialogVisibleFiled" width="30%">
        <span>源字段复制到目标字段，目标字段将被全部覆盖，是否确定复制？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleFiled = false">取 消</el-button>
          <el-button type="primary" @click="copyToTargetField">确 定</el-button>
        </span>
      </el-dialog>
      <!--表格渲染-->
      <div class="limitHeight">
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          size="small"
          stripe
          border
          style="width: 100%;"
          @sort-change="sortChange"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column
            type="index"
            width="50"
            label="序号"
            align="center"
          />
          <el-table-column prop="sourceCode" label="源字段" sortable="custom" />
          <el-table-column
            prop="sourceType"
            label="源字段类型"
            width="110"
            sortable="custom"
          />
          <el-table-column
            prop="sourceSize"
            label="源字段长度"
            align="right"
            width="110"
            sortable="custom"
          />
          <el-table-column prop="targetCode" label="目标字段" sortable="custom">
            <template slot-scope="scope">
              <div class="searchFiled">
                <el-input
                  v-model="scope.row.targetCode"
                  @change="saveRowData(scope.row)"
                />
                <span
                  class="el-icon-zoom-in searchIcon"
                  @click="getField(scope.row)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="memo" label="备注">
            <template slot-scope="scope">
              <div class="cancelRight">
                <el-input
                  v-model="scope.row.memo"
                  @change="saveRowData(scope.row)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
/* eslint-disable */
import crudMigDefItem from "@/api/migrate/migDefItem";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { getColumns, initSourceItems } from "@/api/migrate/coustomFunction";

const defaultForm = {
  id: null,
  migCode: null,
  sourceType: null,
  sourceCode: null,
  sourceSize: null,
  targetCode: null,
  memo: null,
  migRule: null,
  extClass: null,
  extJson: null,
  delFlag: null,
  createTime: null,
  updateTime: null
};
export default {
  name: "MigDefItem",
  components: { pagination, crudOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "迁移数据字段对应",
      //只有在doNotQuery为true的情况下才不走页面初始化时系统的第一次查询
      doNotQuery: true,
      url: "api/migDefItem",
      sort: "sourceCode,asc",
      size: 400,
      crudMethod: { ...crudMigDefItem }
    });
  },
  data() {
    return {
      paramsData: {},
      sourceTableArr: [],
      targetFieldRequest: false,
      loading: false,
      checkedFieldArr: [],
      rowData: {},
      listData: [],
      permission: {
        add: ["admin", "migDefItem:add"],
        edit: ["admin", "migDefItem:edit"],
        del: ["admin", "migDefItem:del"]
      },
      rules: {
        id: [{ required: true, message: "主键不能为空", trigger: "blur" }]
      },
      targetFieldShow: false,
      dialogVisibleFiled: false
    };
  },
  computed: {
    routerParam() {
      return this.$route.query;
    }
  },
  watch: {
    routerParam: {
      handler(val) {
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          target: ".app-container",
          spinner: "el-icon-loading"
        });
        const routeParams = this.$route.query;
        if (routeParams) {
          this.paramsData = routeParams;
        }
        // 查询的标识
        this.query.relation = true;
        this.query.migCode = routeParams.id;
        this.crud.refresh().then(() => {
          loading.close();
        });
      }
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      //不执行查询
      this.query.unQuery = true;
      return true;
    },
    sortChange(data = {}) {
      const prop = data.prop;
      const order =
        data.order == "ascending" || data.order == "asc" ? "asc" : "desc";
      if (prop) {
        this.crud.sort = [`${prop},${order}`];
        this.crud.toQuery();
      }
    },
    [CRUD.HOOK.afterRefresh]() {
      let arr = [];
      this.crud.data.map(i => {
        i.targetCode && arr.push(i.targetCode);
      });
      this.checkedFieldArr = arr;
      return true;
    },
    sortChecked() {
      let arr1 = this.sourceTableArr.filter(i => i.checked == false);
      let arr2 = this.sourceTableArr.filter(i => i.checked == true);
      this.sourceTableArr = [...arr1, ...arr2];
    },
    checkFieldItem(index, label, value) {
      var that = this;
      this.sourceTableArr[index].checked = true;
      this.sortChecked();
      this.targetFieldShow = false;
      this.rowData.targetCode = value;
      crudMigDefItem.edit(this.rowData).then(function(res) {
        that.query.migCode = that.paramsData.id;
        that.crud.refresh();
      });
    },
    saveRowData(item) {
      var that = this;
      this.rowData = item;
      crudMigDefItem.edit(this.rowData).then(function(res) {
        that.query.migCode = that.paramsData.id;
        that.crud.refresh();
      });
    },
    getField(item) {
      this.rowData = item;
      this.targetFieldShow = true;
      if (!this.targetFieldRequest) {
        const params = {
          dsName: this.paramsData.dsName,
          tableName: this.paramsData.tableName
        };
        getColumns(params).then(res => {
          if (res && res.content) {
            const data = res.content;
            this.targetFieldRequest = true;
            const arr = [];
            data.map(i => {
              let len = this.checkedFieldArr.filter(j => i.code == j).length;
              if (len > 0) {
                arr.push({
                  label: i.desc,
                  value: i.code,
                  checked: true
                });
              } else {
                arr.push({
                  label: i.desc,
                  value: i.code,
                  checked: false
                });
              }
            });
            this.sourceTableArr = arr;
            this.sortChecked();
          }
        });
      }
    },
    // 删除
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.crud.delAllLoading = true;
          this.crud.doDelete(datas);
        })
        .catch(() => {});
    },
    // 同步源字段
    asyncFiled() {
      this.loading = true;
      const params = {
        tableName: this.paramsData.table,
        dsName: this.paramsData.fieldName,
        migCode: this.paramsData.id
      };
      if (!this.paramsData.table) {
        this.$message({
          message: "需要设置源数据源表",
          type: "warning"
        });

        this.loading = false;
        return;
      }
      if (!this.paramsData.fieldName) {
        this.$message({
          message: "需要设置源数据字段",
          type: "warning"
        });
        this.loading = false;
        return;
      }
      initSourceItems(params)
        .then((res = {}) => {
          this.query.migCode = this.paramsData.id;
          this.loading = false;
          if (res && res.RTN_CODE && res.RTN_CODE == "ERROR") {
            this.crud.notify(res.MSG, CRUD.NOTIFICATION_TYPE.ERROR);
          }
          this.crud.toQuery();
        })
        .catch(e => {
          this.loading = false;
        });
    },
    asyncTargetFiled() {
      this.dialogVisibleFiled = true;
    },
    copyToTargetField() {
      const that = this;
      if (this.loading) {
        return;
      }
      this.loading = true;
      const migCode = that.query.migCode || that.paramsData.id;
      crudMigDefItem
        .copyTotarget({ migCode })
        .then(res => {
          that.query.migCode = that.paramsData.id;
          this.loading = false;
          that.crud.refresh();
          this.dialogVisibleFiled = false;
        })
        .catch(e => {
          console.error(e.message);
          this.loading = false;
        });
    }
  },
  created() {
    const routeParams = this.$route.query;
    if (routeParams) {
      this.paramsData = routeParams;
    }
    // 查询的标识
    this.query.relation = true;
    this.query.migCode = routeParams.id;
    this.crud.refresh();
  }
};
</script>

<style scoped>
.app-container,
.head-container {
  height: 100%;
}
.limitHeight {
  height: calc(100vh - 200px);
  overflow-y: auto;
}
.check_ul {
  display: flex;
  flex-wrap: wrap;
}
.check_li {
  display: inline-block;
  line-height: 30px;
  height: 30px;
  text-align: center;
  border: 1px solid #eee;
  margin: 0 10px 10px 0;
  padding: 0 8px;
  cursor: pointer;
}
.li_checked {
  background-color: #eee;
}
.searchFiled {
  padding-right: 26px;
  position: relative;
}
.cancelRight {
  position: relative;
}
.searchIcon {
  position: absolute;
  right: 5px;
  top: 6px;
  cursor: pointer;
  font-size: 16px;
  color: #42b983;
}
</style>
